package com.mkj.menu;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @Author Arrebol
 * @Date 2024/8/4 14:20
 * @Project graphical programming
 * @Description：
 * 菜单相关组件
 */
public class SimpleMenuDemo1 {
    Frame frame = new Frame("这里测试菜单相关组件");
    //创建菜单条组件
    MenuBar menuBar = new MenuBar();
    //创建菜单组件
    Menu fileMenu = new Menu("文件");
    Menu editMenu = new Menu("编辑");
    //这是一个子菜单，放在菜单里
    Menu formatMenu = new Menu("格式");
    //创建菜单项组件
    MenuItem autoNewLine = new MenuItem("自动换行");
    MenuItem copy = new MenuItem("复制");
    MenuItem paste = new MenuItem("粘贴");
    //关联快捷键Ctrl+Shift+Q
    MenuItem comment = new MenuItem("注释", new MenuShortcut(KeyEvent.VK_Q, true));
    MenuItem cancelComment = new MenuItem("取消注释");
    //创建文本框
    TextArea textArea = new TextArea(6, 40);

    public static void main(String[] args) {
        new SimpleMenuDemo1().init();
    }

    public void init() {
        //组装视图
        //为子菜单绑定事件
        comment.addActionListener(e -> textArea.append("您点击了菜单项：" + e.getActionCommand()));
        //组装格式子菜单
        formatMenu.add(comment);
        formatMenu.add(cancelComment);
        //组装编辑菜单
        editMenu.add(autoNewLine);
        editMenu.add(copy);
        editMenu.add(paste);
        editMenu.add(formatMenu);
        //将两个菜单加入到MenuBar
        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        //将MenuBar放入到Frame中
        frame.setMenuBar(menuBar);
        //将文本框放入到Frame中
        frame.add(textArea);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.pack();
        frame.setVisible(true);
    }
}
